import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";

// ✅ 正确导入 vue-router（具名导入）
import { createRouter, createWebHistory } from "vue-router";

// 导入组件
import Login from "./components/Login.vue";
import ChatWindow from "./components/ChatWindow.vue";
import Friend from "./components/Friend.vue";
import ChatLayout from "./components/ChatLayout.vue";
import ConversationList from "./components/ConversationList.vue";

// ✅ 创建路由实例
const router = createRouter({
  // ✅ 使用 createWebHistory 替代 mode: 'history'
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      component: Login,
    },
    {
      path: "/chatlayout",
      component: ChatLayout,
      meta: {
        requiresAuth: true,
      },
      redirect: { name: "Conversation" },
      children: [
        // {
        //   path: "",
        //   redirect: "conversation",
        // },
        {
          path: "conversation",
          component: ConversationList,
          name: "Conversation",
        },
        {
          path: "friend",
          component: Friend,
          name: "Friend",
        },
        {
          path: "chatwindow",
          component: ChatWindow,
          name: "ChatWindow",
        },
      ],
    },
  ],
});

// ✅ 全局前置守卫（写法不变，兼容）
router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    const token = localStorage.getItem("token");
    if (!token) {
      next("/"); // 未登录，跳转登录页
    } else {
      next(); // 已登录
    }
  } else {
    next(); // 不需要登录
  }
});

// ✅ 创建 app 实例
const app = createApp(App);

// ✅ 使用插件
app.use(ElementPlus);
const pinia = createPinia();
app.use(pinia);
app.use(router); // ✅ 注册路由

// ✅ 挂载
app.mount("#app");
